/* 
  网络判断，加载过程统一控制 
  url、data、success 必填
  */
import store from '@/store'
const request = function(obj = {}) { // 所有请求入口
	uni.getNetworkType({
		success: function(res) {
			// console.log(res.networkType);
			if (res.networkType === 'none') {
				uni.showToast({
					icon: 'none',
					duration: 5000,
					title: '       网络连接不可用. . .       '
				})
				obj.complete()
			} else {
				netWorkRequest(obj)
			}
		},
		fail: function() {
			netWorkRequest(obj)
		}
	});
}

const netWorkRequest = function(obj) {
	uni.showLoading({
		title: '加载中...',
		mask: true
	})
	uni.request({
		url: obj.url,
		method: obj.method || 'post',
		header: {
			token: store.state.token,
			...obj.header
		},
		data: {
			...obj.data
			// openid: store.state.uid,
		},
		success: res => {
			if (res.statusCode !== 200) { // 全部会返回到 success 无论是否请求成功
				uni.showToast({
					icon: 'none',
					title: "       " + res.statusCode + "  服务出错了. . .       ",
					duration: 5000
				});
				return
			}
			if (res.data.code === -1) {
				uni.showModal({
					title: '登录提示',
					content: '  登录状态过期请重新登录  ',
					showCancel: false,
					success: function(res) {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/login/login'
							})
						}
					}
				});
			}
			if(res.data.code===0){
				uni.showToast({
					title: res.data.msg,
					icon:'none'
				})
			}
			if (obj.success) {
				obj.success(res)
			}
		},
		fail: (res) => {
			uni.showToast({
				icon: 'none',
				title: "  服务出错了. . .       ",
				duration: 5000
			})
			if (obj.fail) {
				obj.fail()
			}
		},
		complete: () => {
			uni.hideLoading()
			if (obj.complete) {
				obj.complete()
			}
		}
	});
}

export default request
